import { VNode, VNodeData } from './vnode'
//将虚拟节点转为真是DOM
export function createElement(node: VNode): Element {
    //将sel元素节点先创建出来
    const ancestors: Element = document.createElement(node.sel)
    //将真实dom放到ele属性上
    node.ele = ancestors
    //将属性设置到节点上去
    setAttribute(ancestors, node.data)

    //将子元素节点都插入到sel上
    if (node.children && node.children.length !== 0) {
        for (let i = 0; i < node.children.length; i++) {
            const children: Element = createElement(node.children[i] as VNode)
            ancestors.appendChild(children);
        }
    } else {
        //如果没有节点了就将文本节点插入进去
        ancestors.textContent = node.text
    }
    return ancestors
}

//将属性添加到DOM上
export function setAttribute(node: Element, props: VNodeData): void {
    for (let key in props) {
        switch (key) {
            case 'class':
                if (typeof props[key] == 'string') {
                    node.className = props[key] as string
                } else if (Array.isArray(props[key])) {
                    node.className = (props[key] as Array<string>).join(' ')
                } else {
                    throw new Error('class必须是字符串或者数组')
                }
                break
            case 'style':
                if (typeof props[key] == 'object' && props[key] !== null) {
                    for (let property in props[key]) {
                        node.style[property] = props[key][property];
                    }
                } else {
                    throw new Error('style必须是对象')
                }
                break
            default:
                node.setAttribute(key, props[key])
                break
        }
    }
}